package me.landery.modules.sinco.rest;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.landery.annotation.AnonymousAccess;
import me.landery.exception.BadRequestException;
import me.landery.modules.sinco.domain.em.GenType;
import me.landery.modules.sinco.service.ModeService;
import me.landery.modules.sinco.service.PaperService;
import me.landery.modules.sinco.service.VipService;
import me.landery.modules.sinco.service.dto.GeneratePaperDto;
import me.landery.modules.sinco.service.dto.VipDto;
import me.landery.utils.SecurityUtils;
import me.landery.utils.StringUtils;
import me.landery.utils.ZxHttpUtil;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Api(tags = "文章：文章操作")
@RequestMapping("/sinco/paper")
public class PaperController {


    private final ModeService modeService;
    private final VipService vipService;
    private final PaperService paperService;


    @ApiOperation("抓取文章")
    @AnonymousAccess
    @PostMapping(value = {"/crawl_title"})
    public ResponseEntity<Object> crawlTitle(@Validated  @RequestBody Map<String, String> map) throws ParserConfigurationException, XPathExpressionException {
        String url = map.get("url");
        String xpath = map.get("xpath");
        if (StringUtils.isNotBlank(url)){
            String html = null;
            try {
                Connection connect = Jsoup.connect(url);
                html = connect.get().body().html();
            } catch (IOException e) {
                e.printStackTrace();
            }
            HtmlCleaner hc = new HtmlCleaner();
            TagNode tn = hc.clean(html);
            Document dom = new DomSerializer(new CleanerProperties()).createDOM(tn);
            XPath xPath = XPathFactory.newInstance().newXPath();
            Object result;
            result = xPath.evaluate(xpath, dom, XPathConstants.NODESET);
            if (result instanceof NodeList) {
                NodeList nodeList = (NodeList) result;
                System.out.println(nodeList.getLength());
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    sb.append(node.getTextContent());
                }
                return new ResponseEntity<>(sb, HttpStatus.OK);

            }
        }else{
            throw new BadRequestException("未获取到网页数据");
        }
        return  new ResponseEntity<>("无法抓取该网页", HttpStatus.NOT_FOUND);

    }

    @ApiOperation("检测文章语种")
    @AnonymousAccess
    @PostMapping(value = {"/detect_lang"})
    public ResponseEntity<Object> detectLang(@Validated  @RequestBody Map<String, String> map) throws Exception {
        String url = "https://fanyi.baidu.com/langdetect?";
        String content = map.get("content");
        Map<String, String> params = new HashMap<>();
        params.put("query", content);
        String output = ZxHttpUtil.sendPostMessage(
                url,
                params,
                "utf-8",
                "BIDUPSID=0D91F06A03249152CDD39DA73825E3DF; PSTM=1636470919; __yjs_duid=1_832ad303a924168295d39101c6fd57d01636540713342; BDUSS=Bnd004c1dXcGwwR05IejlCdHBBU3pnVX51VGZmN3A3cVFkLWw1eWZNS3RYNnhpSVFBQUFBJCQAAAAAAAAAAAEAAAAE4K0wtsDB9NK5x-kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK3ShGKt0oRiWT; BDUSS_BFESS=Bnd004c1dXcGwwR05IejlCdHBBU3pnVX51VGZmN3A3cVFkLWw1eWZNS3RYNnhpSVFBQUFBJCQAAAAAAAAAAAEAAAAE4K0wtsDB9NK5x-kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK3ShGKt0oRiWT; H_WISE_SIDS=107316_110085_127969_184716_190624_194085_194519_196425_196528_197241_197711_197955_199575_201193_203880_203882_203885_204713_204715_204717_204720_204860_204916_205420_205424_205710_205859_206704_207235_207729_208607_208721_208804_208972_209160_209345_209568_209847_210095_210304_210791_210971_211016_211289_211456_211558_211580_211740_212295_212416_212533_212543_212617_212701_212739_212744_212772_212874_212908_212993_213032_213059_213070_213362_213401_213415_213553_213566_213596_213642_213644_214006_214025_214108_214128_214136_214148_214233_214536_214654_214788_214803_215146_215280; MCITY=-%3A; BAIDUID=EB07BA33A8D3DF7D4609A2FE9A8DACBD:SL=0:NR=10:FG=1; H_PS_PSSID=31253_26350; BDSFRCVID=tbPOJexroG0C39jDmdmXuaF0zeKKvXOTDYLEOwXPsp3LGJLVg9ZpEG0Pt89L1utbMRWcogKKXgOTHw0F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tRAOoC8atDvbfP0kK-Qfb-A8KMQbKP7-HDOH05rJaDvTHj6Oy4oTj6jW-J6Z0tjRW56l-t5q3DJ0eqTmW6853MvBbG-L2f5I5HRDQJTE5DjW_PQsQft20M0EeMtjBM_LLbr4QR7jWhviep72ybt2QlRX5q79atTMfNTJ-qcH0KQpsIJM5-DWbT8IjHCHJ5LjfnuqVIvt-5rDHJTg5DTjhPrMBUTRWMT-MTryKKJ4aC0bshvRKp5h-f5Q2xoiB5OMBanRhlRNB-3iV-OxDUvnyxAZbn3ZQMQxtNRJQb5S0-cTHCocyU7obUPUWMJ9LUvftgcdot5yBbc8eIna5hjkbfJBQttjQn3hfIkj2CKLtDKahK8mDT835n-Wqxny2P_XKK_sVlboBhcqEIL4jPvAy4KeQ-RX-MQfMg8tbfbxMlFBjxbSj4QoMToLMh525tolQgrK-pvIJ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mVk"
        );
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(output);
        return  new ResponseEntity<>(jsonObject, HttpStatus.OK);
    }

//    @ApiOperation("生成文章标题")
//    @PostMapping(value = {"/gentitle"})
//    public ResponseEntity<Object> generateTitle(@RequestBody JSONObject jsonObject,HttpServletRequest request){
//        String paper = jsonObject.getString("paper");
//        //获取当前用户
//        Long userId = SecurityUtils.getCurrentUserId();
////        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
////        HttpServletRequest request = (HttpServletRequest)requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
//        // 查询当前用户的套餐等
//        VipDto userVip = vipService.findByUserID(userId);
//
//        String title = paperService.generateResult(userVip,paper, GenType.TITLE.getValue(), null,request);
//
//        return new ResponseEntity<>(title, HttpStatus.OK);
//    }


//    @ApiOperation("生成文章摘要")
//    @PostMapping(value = {"/genAbstract"})
//    public ResponseEntity<Object> generateAbstract(@RequestBody JSONObject jsonObject,HttpServletRequest request){
//        String paper = jsonObject.getString("paper");
//        //获取当前用户
//        Long userId = SecurityUtils.getCurrentUserId();
//
//        // 查询当前用户的套餐等
//        VipDto userVip = vipService.findByUserID(userId);
//
//        String p_abstract = paperService.generateResult(userVip,paper,GenType.ABSTRACT.getValue(),null,request);
//
//        return new ResponseEntity<>(p_abstract, HttpStatus.OK);
//    }
//
//    @ApiOperation("根据token生成文章标题")
//    @AnonymousAccess
//    @PostMapping(value = {"/genTitleByToken"})
//    public ResponseEntity<Object> generateTitleByToken(@RequestBody JSONObject jsonObject,HttpServletRequest request){
//        String title = paperService.generateResultByToken(jsonObject,request);
//        return new ResponseEntity<>(title, HttpStatus.OK);
//    }

    /**
     * 统一调用接口，需要登陆
     */
    @ApiOperation("统一调用接口")
    @PostMapping(value = {"/genResult"})
    @PreAuthorize("@el.check('paper:genResult','admin')")
    public ResponseEntity<Object> generateResult(@Validated @RequestBody  GeneratePaperDto generatePaperDto, HttpServletRequest request){
        return new ResponseEntity<>(paperService.generateResultEntrance(generatePaperDto,request), HttpStatus.OK);
    }

    /**
     * 统一调用接口，token
     */
    @ApiOperation("统一调用接口")
    @PostMapping(value = {"/genResultByToken"})
    @AnonymousAccess
    public ResponseEntity<Object> generateResultByToken(@Validated @RequestBody  GeneratePaperDto generatePaperDto, HttpServletRequest request){
        return new ResponseEntity<>(paperService.generateResultEntrance(generatePaperDto,request), HttpStatus.OK);
    }
}
